﻿(function (window) {
    var SpeechServer = 'http://wa.eguidedog.net';
    var speechQueue = [];
    var speechId = 0;

    var englishTTS = SpeechServer + '/cgi-bin/espeak.pl?cache=1&text=';
    var mandarinTTS = SpeechServer + '/cgi-bin/ekho.pl?voice=mandarin&cache=1&text=';
    var fastMandarinTTS = SpeechServer + '/cgi-bin/ekho.pl?voice=fast_mandarin&cache=1&text=';
    var hindiTTS = SpeechServer + '/cgi-bin/espeak.pl?voice=hi&cache=1&text=';
    var frenchTTS = SpeechServer + '/cgi-bin/espeak.pl?voice=fr&cache=1&text=';
    var germanTTS = SpeechServer + '/cgi-bin/espeak.pl?voice=de&cache=1&text=';
    var cantoneseTTS = SpeechServer + '/cgi-bin/ekho.pl?voice=cantonese&cache=1&text=';
    var fastCantoneseTTS = SpeechServer + '/cgi-bin/ekho.pl?voice=fast_cantonese&cache=1&text=';

    var language = "Mandarin";
    var ttsServer = mandarinTTS;

    /*
        tts引擎对象
    */
    var TTS = {};

    //是否可用
    TTS.isEnable = false;

    /*
        启用语音合成引擎
        参数:
          --语言
    */
    TTS.enable = function (lang) {
        if (!(new Audio().canPlayType("audio/mpeg"))) return;
        TTS.isEnable = true;
        language = (lang || language);
        switch (language)
        {
            //汉语
            case 'Mandarin': ttsServer = mandarinTTS; break;
                //快速汉语
            case 'FastMandarin': ttsServer = fastMandarinTTS; break;
            case 'Hindi': ttsServer = hindiTTS; break;
            case 'French': ttsServer = frenchTTS; break;
            case 'German': ttsServer = germanTTS; break;
                //粤语
            case 'Cantonese': ttsServer = cantoneseTTS; break;
                //快速粤语
            case 'FastCantonese': ttsServer = fastCantoneseTTS; break;
                //英语
            case 'English': // keep English last as default
            default: ttsServer = englishTTS;
        }
    };

    /*
        朗读
        参数:
          --文本
    */
    TTS.speak = function (text) {
        if (!TTS.isEnable) return;
        var rNum = ((Math.random() * 200) >> 0) + "" + ((Math.random() * 2000) >> 0);
        audio.load("speaker" + rNum, "!" + ttsServer + escape(text), function (o) {
            o.addEventListener("ended", function () {
                speechQueue[speechId] = null;
                speechId++;
                audio.remove("speaker" + rNum);
                if (speechId != speechQueue.length)
                {
                    speechQueue[speechId].play();
                }
            });
            speechQueue.add(o);
            if (speechId != speechQueue.length)
            {
                speechQueue[speechId].play();
            }
        });
    };

    window.tts = TTS;
})(window);